package com.mspbots.web.reports.filter;

import com.mspbots.web.reports.MessageReportsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Slf4j
@Component
public class PageviewsFilter implements GlobalFilter, Ordered {

    @Autowired
    private MessageReportsService messageReportsService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        HttpHeaders httpHeaders = request.getHeaders();

        log.debug("Request path [{}]", path.pathWithinApplication().value());

        if (!Objects.isNull(httpHeaders.getFirst("tenantId"))
                && !Objects.isNull(httpHeaders.getFirst("userName"))) {
            messageReportsService.pageViewsMessage(Long.valueOf(httpHeaders.getFirst("tenantId")),
                    httpHeaders.getFirst("userName"), path.pathWithinApplication().value(),
                    request.getRemoteAddress().getAddress().getHostAddress());
        }

        ServerWebExchange mutatedServerWebExchange = exchange.mutate().request(request).build();

        return chain.filter(mutatedServerWebExchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
